package kr.ac.mju.mdc.mjuapp.traffic;

import java.util.Timer;
import java.util.TimerTask;

import kr.ac.mju.mdc.mjuapp.R;
import kr.ac.mju.mdc.mjuapp.network.NetworkManager;
import kr.ac.mju.mdc.mjuapp.util.PixelConverter;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author davidkim
 *
 */
public class TrafficActivity extends Activity implements OnClickListener, OnTouchListener {
	private final int LOADING_DIALOG = 10;
	private final int SLIDING_MOVE_LEFT = 11;
	private final int SLIDING_MOVE_RIGHT = 12;

	private boolean isOpened = false;

	private int leftMax = 0;
	private int leftMin = 0;

	private float oldX = 0;
	private float upOldX = 0;

	private Timer slidingTimer = null;
	private TimerTask slidingTimerTask = null;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			int what = msg.what;
			switch (what) {
			case SLIDING_MOVE_LEFT:
				slidingTimer = new Timer();
				slidingTimerTask = new TimerTask() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						handler.post(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								View contentView = findViewById(R.id.traffic_content);
								// right to left
								if (contentView.getLeft() <= leftMin) {
									contentView.layout(0, contentView.getTop(), contentView.getRight(), contentView.getBottom());
									stopSlidingTimer();
									oldX = 0;
									upOldX = 0;
									isOpened = false;
									findViewById(R.id.traffic_left_slidingbar).setClickable(false);
								} else {
									contentView.layout(contentView.getLeft() - 15, contentView.getTop(), contentView.getRight() - 15,
											contentView.getBottom());
								}
							}
						});
					}
				};
				slidingTimer.schedule(slidingTimerTask, 0, 5);
				break;
			case SLIDING_MOVE_RIGHT:
				slidingTimer = new Timer();
				slidingTimerTask = new TimerTask() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						handler.post(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								View contentView = findViewById(R.id.traffic_content);
								// to right
								if (contentView.getLeft() >= leftMax) {
									contentView.layout(leftMax, contentView.getTop(), leftMax + contentView.getRight(),
											contentView.getBottom());
									stopSlidingTimer();
									oldX = 0;
									upOldX = 0;
									isOpened = true;
									findViewById(R.id.traffic_left_slidingbar).setClickable(true);
								} else {
									contentView.layout(contentView.getLeft() + 15, contentView.getTop(), contentView.getRight() + 15,
											contentView.getBottom());
								}
							}
						});
					}
				};
				slidingTimer.schedule(slidingTimerTask, 0, 5);
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.traffic_layout);
		//init
		init();
		//initlayout
		initLayout();
		//
		if (NetworkManager.checkNetwork(getApplicationContext())) {
			WebView wv = (WebView) findViewById(R.id.traffic_webview);
			wv.loadUrl("http://www.mju.ac.kr/mbs/mjumob2/subview.jsp?id=mjumob_040103000000");
			wv.setWebViewClient(new WebViewClient() {
				@Override
				public void onPageStarted(WebView view, String url, Bitmap favicon) {
					// TODO Auto-generated method stub
					super.onPageStarted(view, url, favicon);
					showDialog(LOADING_DIALOG);
				}

				@Override
				public void onPageFinished(WebView view, String url) {
					// TODO Auto-generated method stub
					super.onPageFinished(view, url);
					dismissDialog(LOADING_DIALOG);
				}

				@Override
				public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
					// TODO Auto-generated method stub
					super.onReceivedError(view, errorCode, description, failingUrl);
					Toast.makeText(getApplicationContext(), "onReceivedError : " + errorCode + ", " + description, Toast.LENGTH_LONG)
							.show();
					// error 시 white page 출력
					String blankPage = "<html><body></body></html>";
					view.loadData(blankPage, "text/html", "utf-8");
				}
			});
		}
		findViewById(R.id.traffic_liberalarts_shuttlebus).setOnClickListener(this);
		findViewById(R.id.traffic_liberalarts_urbanbus).setOnClickListener(this);
		findViewById(R.id.traffic_liberalarts_subway).setOnClickListener(this);
		findViewById(R.id.traffic_science_schoolbus_gotoschool).setOnClickListener(this);
		findViewById(R.id.traffic_science_schoolbus_walkhome).setOnClickListener(this);
		findViewById(R.id.traffic_science_shuttle_semester_weekday).setOnClickListener(this);
		findViewById(R.id.traffic_science_shuttle_semester_weekend).setOnClickListener(this);
		findViewById(R.id.traffic_science_shuttle_vacation).setOnClickListener(this);
		findViewById(R.id.traffic_between_liberalarts_and_science_gotoschool).setOnClickListener(this);
		findViewById(R.id.traffic_between_liberalarts_and_science_walkhome).setOnClickListener(this);
		findViewById(R.id.traffic_sliding_btn).setOnTouchListener(this);
		findViewById(R.id.traffic_left_slidingbar).setOnTouchListener(this);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case LOADING_DIALOG:
			Dialog progressDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
			progressDialog.setContentView(R.layout.loading_progress);
			progressDialog.setCancelable(false);
			return progressDialog;
		default:
			return null;
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (isOpened)
			handler.sendEmptyMessage(SLIDING_MOVE_LEFT);
		else
			super.onBackPressed();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (NetworkManager.checkNetwork(getApplicationContext())) {
			String url = null;
			TextView titleView = (TextView) findViewById(R.id.traffic_title);
			int id = v.getId();
			switch (id) {
			case R.id.traffic_liberalarts_shuttlebus:
				url = "http://www.mju.ac.kr/mbs/mjumob2/subview.jsp?id=mjumob_040103000000";
				titleView.setText("명지셔틀버스");
				break;
			case R.id.traffic_liberalarts_urbanbus:
				url = "http://www.mju.ac.kr/mbs/mjumob2/subview.jsp?id=mjumob_040101000000";
				titleView.setText("일반시내버스");
				break;
			case R.id.traffic_liberalarts_subway:
				url = "http://www.mju.ac.kr/mbs/mjumob2/subview.jsp?id=mjumob_040102000000";
				titleView.setText("지하철");
				break;
			case R.id.traffic_science_schoolbus_gotoschool:
				url = "http://www.mju.ac.kr/mbs/mjumob2/subview.jsp?id=mjumob_040201000000";
				titleView.setText("통학버스(등교)");
				break;
			case R.id.traffic_science_schoolbus_walkhome:
				url = "http://www.mju.ac.kr/mbs/mjumob2/subview.jsp?id=mjumob_040202000000";
				titleView.setText("통학버스(하교)");
				break;
			case R.id.traffic_science_shuttle_semester_weekday:
				url = "http://www.mju.ac.kr/mbs/mjumob2/subview.jsp?id=mjumob_040203000000";
				titleView.setText("셔틀버스(학기중:평일)");
				break;
			case R.id.traffic_science_shuttle_semester_weekend:
				url = "http://www.mju.ac.kr/mbs/mjumob2/subview.jsp?id=mjumob_040204000000";
				titleView.setText("셔틀버스(학기중:공휴일)");
				break;
			case R.id.traffic_science_shuttle_vacation:
				url = "http://www.mju.ac.kr/mbs/mjumob2/subview.jsp?id=mjumob_040205000000";
				titleView.setText("셔틀버스(방학중)");
				break;
			case R.id.traffic_between_liberalarts_and_science_gotoschool:
				url = "http://www.mju.ac.kr/mbs/mjumob2/subview.jsp?id=mjumob_040206000000";
				titleView.setText("인문/자연간 셔틀버스(등교)");
				break;
			case R.id.traffic_between_liberalarts_and_science_walkhome:
				url = "http://www.mju.ac.kr/mbs/mjumob2/subview.jsp?id=mjumob_040207000000";
				titleView.setText("인문/자연간 셔틀버스(하교)");
				break;
			}
			((WebView) findViewById(R.id.traffic_webview)).loadUrl(url);
			if (isOpened)
				handler.sendEmptyMessage(SLIDING_MOVE_LEFT);
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_MOVE) {
			float currentX = event.getRawX();
			if (oldX == 0.)
				oldX = currentX;
			// drag
			View view = findViewById(R.id.traffic_content);
			if (view.getLeft() <= leftMax && view.getLeft() >= leftMin) {
				view.layout((int) (view.getLeft() - (oldX - currentX)), view.getTop(), (int) (view.getRight() - (oldX - currentX)),
						view.getBottom());
				upOldX = oldX;
				oldX = currentX;
			}
		} else if (event.getAction() == MotionEvent.ACTION_UP) {
			final float currentX = event.getRawX();
			// direction
			float direction = upOldX - currentX;
			if (isOpened)
				handler.sendEmptyMessage(SLIDING_MOVE_LEFT);
			else if (!isOpened)
				handler.sendEmptyMessage(SLIDING_MOVE_RIGHT);
			else if (direction > 0)
				handler.sendEmptyMessage(SLIDING_MOVE_LEFT);
			else if (direction < 0)
				handler.sendEmptyMessage(SLIDING_MOVE_RIGHT);
		}
		return false;
	}

	/**
	 * 
	 */
	private void init() {
		isOpened = false;
		oldX = 0;
		upOldX = 0;
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		PixelConverter converter = new PixelConverter(this);
		leftMax = (int) ((float)displaymetrics.widthPixels - converter.getWidth(135));
		leftMin = 0;
	}
	/**
	 * 
	 */
	private void initLayout(){
		PixelConverter converter = new PixelConverter(this);
		RelativeLayout.LayoutParams rParams = null;
		rParams = (LayoutParams) findViewById(R.id.traffic_sub_layout).getLayoutParams();
		rParams.rightMargin = converter.getWidth(135);
		findViewById(R.id.traffic_sub_layout).setLayoutParams(rParams);
	}
	/**
	 * 
	 */
	private void stopSlidingTimer() {
		if (slidingTimerTask != null) {
			slidingTimerTask.cancel();
			slidingTimerTask = null;
		}
		if (slidingTimer != null) {
			slidingTimer.purge();
			slidingTimer.cancel();
			slidingTimer = null;
		}
	}
}
/* end of file */
